<template>
  <div class="add-user-to-club">
    <!-- 社团信息-->
    <el-card class="club-info">
      <template #header>
        <h3>社团信息</h3>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="社团编号">
          {{ clubInfo.id }}
        </el-descriptions-item>
        <el-descriptions-item label="社团名称">
          {{ clubInfo.name }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 用户查询 -->
    <el-card class="user-search">
      <template #header>
        <h3>查询用户</h3>
      </template>
      <el-input
        v-model="userIdInput"
        placeholder="请输入用户编号"
        class="input-with-select"
      >
        <template #append>
          <el-button @click="searchUser">查询</el-button>
        </template>
      </el-input></el-card
    >

    <!-- 用户信息显示 -->
    <el-card v-if="userInfo" class="user-info">
      <template #header>
        <h3>用户信息</h3>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户编号">
          {{ userInfo.id }}
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ userInfo.userName }}
        </el-descriptions-item>
        <el-descriptions-item label="年级">
          {{ userInfo.grade }}
        </el-descriptions-item>
        <el-descriptions-item label="专业">
          {{ userInfo.major }}
        </el-descriptions-item>
        <el-descriptions-item label="班级">
          {{ userInfo.userClass }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 用户不存在提示 -->
    <el-alert
      v-if="showNoUserAlert"
      title="目标用户不存在"
      type="warning"
      :closable="false"
    />

    <!-- 确认添加按钮 -->
    <el-button type="primary" class="confirm-button" @click="confirmAddUser">
      确认添加
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { type Action, ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "../../../stores/user.ts";
import {
  AdminClubControllerService,
  AdminUserControllerService,
  ClubControllerService,
  type ClubMembershipAddRequest,
} from "../../../../generated";

// 定义社团信息
const clubInfo = ref({
  id: 0,
  name: "",
});

const loadData = async () => {
  const store = useUserStore();
  try {
    const clubResponse = await ClubControllerService.getClubVoById(
      store.managedClubId,
    );
    if (clubResponse.code === 0 && clubResponse.data) {
      clubInfo.value = {
        id: clubResponse.data.id as number,
        name: clubResponse.data.clubName as string,
      };
    } else {
      clubInfo.value = null; // 如果数据为空或格式不正确，设置为 null
      ElMessage.error("加载社团详情失败:" + clubResponse.message);
    }
  } catch (error) {
    clubInfo.value = null; // 如果接口调用失败，设置为 null
    console.error("加载数据时发生错误:", error.message || error);
  }
};

onMounted(() => {
  loadData();
});

// 用户ID输入
const userIdInput = ref("");

// 用户信息
const userInfo = ref<{
  id: number;
  userName: string;
  grade: string;
  major: string;
  userClass: string;
} | null>(null);

// 控制是否显示用户不存在的提示
const showNoUserAlert = ref(false);

// 查询用户信息
const searchUser = async () => {
  // 重置状态
  userInfo.value = null;
  showNoUserAlert.value = false;

  if (!userIdInput.value) {
    ElMessage.warning("请输入用户编号");
    return;
  }

  try {
    const userResponse = await AdminUserControllerService.getUserVoById(
      Number(userIdInput.value),
    );
    if (userResponse.code === 0) {
      userInfo.value = userResponse.data;
    } else {
      showNoUserAlert.value = true;
    }
  } catch (error) {
    console.error("查询用户信息失败:", error);
    ElMessage.error("查询用户信息失败，请重试");
  }
};

// 确认添加用户到社团
const confirmAddUser = async () => {
  if (!userInfo.value) {
    ElMessage.warning("用户信息为空，请先查询用户");
    return;
  }

  try {
    const request: ClubMembershipAddRequest = {
      clubId: clubInfo.value.id as number,
      userId: userInfo.value.id as number,
    };
    const res = await AdminClubControllerService.addMemberToClub(request);

    if (res.code === 0) {
      const successStr = `用户 ${userInfo.value.userName} 已成功添加到社团`;
      ElMessageBox.alert(successStr, "添加成功", {
        confirmButtonText: "确定",
        callback: (action: Action) => {
          if (action === "confirm") {
            try {
              // 重置状态
              userIdInput.value = "";
              userInfo.value = null;
            } catch (e) {
              ElMessage({
                type: "info",
                message: "无法自动重置页面状态，请手动刷新页面。",
                duration: 0,
                showClose: true,
              });
            }
          }
        },
      });
    } else {
      const errorStr = "错误原因: " + res.message;
      ElMessageBox.alert(errorStr, "添加失败", {
        confirmButtonText: "确定",
        callback: (action: Action) => {
          if (action === "confirm") {
            window.location.reload(); // 刷新当前页面
          }
        },
      });
    }
  } catch (error) {
    console.error("添加用户到社团失败:", error);
    ElMessageBox.alert("添加用户到社团时发生错误，请稍后重试。", "系统错误", {
      confirmButtonText: "确定",
      type: "error",
    });
  }
};
</script>

<style scoped>
.add-user-to-club {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.club-info,
.user-search,
.user-info {
  margin-bottom: 20px;
}

.input-with-select {
  margin-bottom: 15px;
}

.confirm-button {
  width: 100%;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>
